package com.validations;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

@Named
public class ActivityValidator implements Validator {
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		Date finishDate = (Date) value;
		UIInput startDateUI = (UIInput) component.getAttributes().get(
				"startDate");

		Date startDate = (Date) startDateUI.getValue();
		if(startDate == null)
		{
			DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
			try {
				startDate = (Date) dateFormat.parse((String) startDateUI.getSubmittedValue());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (startDate != null && finishDate != null
				&& finishDate.before(startDate)) {
			throw new ValidatorException(new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "",
					"La fecha de finalizacion no puede ser anterior "
							+ "a la fecha de inicio"));
		}
	}
}